<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport">
    <title>web客服插件</title>
    <link rel="stylesheet" type="text/css" href="__ROOT__/static/css/hui.css"/>
    <link rel="stylesheet" type="text/css" href="__ROOT__/static/css/material/materialdesignicons.min.css"/>
    <link rel="stylesheet" type="text/css" href="__ROOT__/static/css/my_css.css"/>
    <style>

        .my-time-tips{
            position: absolute;
            left: 0px;
            top: -10px;
            line-height: 0;
            font-size: 10px;
            white-space: nowrap;
            text-align: left;
            font-style: normal;
            color: #ababab;
        }
        .r-time{
            left: auto;
            right: 0;
        }

        .layui-layer-shade {
            background-color: #888888 !important;
        }

        #msg-ul li .emoji_icon{
            position: relative !important;
            top: 6px !important;
            left: 2px !important;
            margin-right: 3px !important;
        }

        #msg-list-box {
            padding: 15px;
            top: 30px;
            margin-bottom: 210px;
        }

        li {
            list-style: none;
            margin: 10px 0;
            min-height: 70px;
        }

        .y-chat-user {
            position: absolute;
            left: 6px;
        }

        .y-chat-user img {
            width: 50px;
            height: 50px;
            border-radius: 50px;
        }

        .y-chat-text {
            position: relative;
            line-height: 22px;
            padding: 8px 12px;
            background-color: #80d1ff;
            border-radius: 3px;
            color: #ffffff;
            word-break: break-all;
            display: inline-block;
            font-size: 15px;
            max-width: 600px;
            min-width: 30px;
            min-height: 22px;
            overflow: unset;
        }

        .user-text {
            /*left: 16px;*/
            margin: 0 49px;
            margin-right: 0;
            margin-top: 5px;
            background-color: #ffffff;
            color: #686868;
            box-shadow: 0px 0px 5px rgb(216, 210, 199);
        }

        /*我的*/
        .y-chat-main ul .y-chat-mine {
            text-align: right;
            padding-left: 0;
            /*padding-right: 60px;*/
        }

        .y-chat-mine .y-chat-user {
            left: auto;
            right: 6px;
        }

        .y-chat-mine .y-chat-text {
            text-align: left;
            /*background-color: #9a87ef;*/
            /*color: #fff;*/
            margin: 0 49px;
            margin-left: 0;
            margin-top: 5px;
            background: white;
            box-shadow: 0px 0px 5px rgb(223, 216, 255);
            color: #9a87ef;
        }

        .y-chat-mine .y-chat-text:after {
            left: auto;
            right: -16px;
            border-top-color: #9a87ef;
            -webkit-transform: rotate(270deg);
            -moz-transform: rotate(270deg);
        }


        /*我的完*/

        .y-chat-text:after {
            opacity: 0;
            content: '';
            position: absolute;
            left: -16px;
            top: 6px;
            width: 0;
            height: 0;
            border-style: solid dashed dashed;
            border-color: #80d1ff transparent transparent;
            overflow: hidden;
            border-width: 10px;
            -moz-transform: rotate(90deg);
            -webkit-transform: rotate(90deg);
        }


        .my-footer {
            box-shadow: none !important;
            height: 180px !important;
            background: white !important;
            border-top: 1px solid #f6f8f9;
        }

        .hui-form-textarea textarea {
            width: 100%;
            height: 100%;
            background: white;
            padding: 10px;
        }


        .my-bottom-btn button {
            width: 25%;
            height: 100%;
            border: none;
            border-radius: unset;
            outline: none;
            box-shadow: none;
            background-color: #F6F8F9 !important;
        }
        .my-bottom-btn button i{
            cursor: pointer;
        }
    </style>
</head>
<body style="background: #fffdf9;">


<header class="hui-header">
    <h1 style="color: white; padding-left: 10px; text-align: left;">
        <i style="color: white;" class="mdi mdi-arrow-left" onclick="javascript:history.go(-1);"></i>
        <span id="html_name" style="    font-size: 13px;
    margin-left: 5px;
    color: white;
    margin-top: 0px;
    position: absolute;">···</span>
    </h1>
</header>

<div class="hui-wrap" style="margin-top: 10px;height: 100%">
    <div class="mescroll" id="mescroll" style="top: 35px">
        <div id="msg-list-box" class="y-chat-main" style="">
        <ul id="msg-ul">


        </ul>
    </div>
    </div>
    <div id="hui-footer" class="my-footer">
        <div class="hui-form-textarea" style="padding: 0;overflow: auto;width: 100%;height: 70%">
            <textarea id="content" placeholder="请输入发送内容..." class="sendMsg" name="sendMsg" style="color: #6a799c;"></textarea>
        </div>
        <div class="my-bottom-btn" style="width: 100%; height: 30%; bottom: 0; position: absolute;">
            <button type="button" class="hui-button hui-fl" style="color: #258df5 ">
                <i id="emoji-btn"  style=" width: 100%;display: block;"class="mdi mdi-emoticon-happy"></i></button>
            <button data-ripple="ripple" type="button" class="hui-button hui-fl" style="color: #258df5 ">
                <i lay-tips="文件选择" class="mdi mdi-file-multiple"></i></button>
            <button data-ripple="ripple" type="button" class="hui-button hui-fl" style="color: #258df5">
                <i lay-tips="发送图片" class="mdi mdi-folder-multiple-image"></i></button>
            <button data-ripple="ripple" type="button" class="hui-button hui-fl sendBtn" style=" "><i
                    class="mdi mdi-send my-send-icon"></i></button>
        </div>
    </div>

</div>


<script type="text/javascript" src="__ROOT__/static/js/jquery2.js" charset="utf-8"></script>
<script type="text/javascript" src="__ROOT__/static/js/jquery.cookie.js"></script>
<script type="text/javascript" src="__ROOT__/static/js/my_config.js" charset="utf-8"></script>
<script type="text/javascript" src="__ROOT__/static/js/hui.js" charset="UTF-8"></script>
<script type="text/javascript" src="__ROOT__/static/js/hui-form.js" charset="utf-8"></script>
<script type="text/javascript" src="__ROOT__/static/js/ripple.min.js" charset="utf-8"></script>

<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
<script type="text/javascript" src="__ROOT__/static/js/config_layui.js" charset="utf-8"></script>

<!--下拉组件-->
<link rel="stylesheet" href="__ROOT__/static/mescroll/dist/mescroll.min.css">
<link rel="stylesheet" href="__ROOT__/static/mescroll/option/mescroll-option.css">
<style type="text/css">
    * {
        margin: 0;
        padding: 0;
        -webkit-touch-callout:none;
        -webkit-tap-highlight-color:transparent;
    }
    ul{list-style-type: none}

    /*列表*/
    .mescroll{
        position: fixed;
        /*top: 50px;*/
        /*bottom: 51px;*/
        top: 10px;
        /*bottom: 180px;*/
        /*height: auto;*/
    }
    /*回到顶部按钮*/
    .mescroll-totop {
        bottom: 70px;
        background-color: #f3f2f2;
        text-align: center;
        opacity: 0.7;
        width: 42px;
        height: 42px;
        line-height: 42px;
    }
    .mescroll-upwarp{
        background: #fffdf9;
        padding-bottom: 0;
    }
</style>
<script src="__ROOT__/static/mescroll/dist/mescroll.min.js" type="text/javascript" charset="utf-8"></script>
<script src="__ROOT__/static/mescroll/option/mescroll-option.js" type="text/javascript" charset="utf-8"></script>
<!--下拉组件end-->

<!--表情包相关-->
<link rel="stylesheet" href="__ROOT__/static/emoji/jquery.emoji.css">
<link rel="stylesheet" href="__ROOT__/static/emoji/jquery.mCustomScrollbar.min.css">
<script src="__ROOT__/static/emoji/jquery.mousewheel-3.0.6.min.js" type="text/javascript" charset="utf-8"></script>
<script src="__ROOT__/static/emoji/jquery.mCustomScrollbar.min.js" type="text/javascript" charset="utf-8"></script>
<script src="__ROOT__/static/emoji/jquery.emoji.js" type="text/javascript" charset="utf-8"></script>
<style>

    .emoji_container{
        top:50% !important;
        left: 1% !important;
        z-index: 9999999999999999999;
    }
    .emoji_container {
        width: 98% !important;
        border: 1px solid #d3d3d3 !important;
        box-shadow: 0 0 4px rgba(0, 0, 0, 0.176) !important;
    }
    .emoji_content ul li {
        width: 16.5% !important;
    }
</style>
<script>
    $("#content").emoji({
        button: "#emoji-btn",
        showTab: false,
        animation: 'fade',
        icons: [
            // {
            //     name: "百度贴吧",
            //     path: "dist/img/tieba/",
            //     maxNum: 50,
            //     file: ".jpg",
            //     placeholder: "#bd_{alias}#",
            // },
            {
                name: "QQ",
                path: "dist/img/qq/",
                maxNum: 91,
                excludeNums: [41, 45, 54],
                file: ".gif",
                placeholder: "#qq_{alias}#"
            },
            // {
            //     name: "新浪",
            //     path: "dist/img/xl/",
            //     maxNum: 101,
            //     file: ".png",
            //     placeholder: "#xl_{alias}#"
            // }
        ]
    });

    //自定义表情格式替换
    function replace_em(str) {
        str = str.replace(/\</g, '&lt;');
        str = str.replace(/\>/g, '&gt;');
        str = str.replace(/\n/g, '<br/>');
        str = str.replace(/\#qq_([0-9]*)#/g, "<img class='emoji_icon' src='dist/img/qq/$1.gif' />");
        return str;
    }
</script>
<!--end-->

<!--点击发送按钮-->
<script type="text/javascript">
    new Ripple({
        opacity: 0.2,  //水波纹透明度
        speed: 0.6,      //水波纹扩散速度
        bgColor: "#67c8ff", //水波纹颜色
        cursor: false  //是否显示手型指针
    });

    /*初始化 发送按钮*/
    if ($(".sendMsg").val() === "") {
        $(".sendBtn").attr("disabled", 'true');
    }

    /*监听表情包点击*/
    $('.emoji_icons li').click(function () {
        $(".sendBtn").attr("disabled", 'false');
        $('.sendBtn').removeAttr("disabled");
        $('.my-send-icon').css('color', ' #258df5');
    });

    /*监听输入框--实时输入内容*/
    $('textarea').bind('input propertychange', function () {

        if ($(".sendMsg").val() === "") {
            $(".sendBtn").attr("disabled", 'true');
            $('.my-send-icon').css('color', ' #656B79');
        } else {
            $(".sendBtn").attr("disabled", 'false');
            $('.sendBtn').removeAttr("disabled");
            $('.my-send-icon').css('color', ' #258df5');
        }
    });

    //点击发送按钮
    hui('.sendBtn').click(function () {
        if ($(".sendMsg").val() === "") {
            hui.toast('不能发送空消息');
            return false;
        }

        var content = $(".sendMsg").val();
        content = replace_em(content);
        showSendMessage(content);

        $.ajax({
            type: "POST",
            data: {
                'to_uid': getUrlParam('uid'),
                'message': $(".sendMsg").val()
            },
            url: "/app/websocket/test/replyMessageToUser.html",
            dataType: "json",
            success: function (res) {
                //清空文本框
                $(".sendMsg").val('');
                $(".sendBtn").attr("disabled", 'true');
                $('.my-send-icon').css('color', ' #656B79');

                if (!res.code)
                {
                    hui.toast('发送失败：'+res.msg);
                }


            },
            error: function (res) {
                console.log(res);
            }
        });

    });
</script>
<!--end-->

<!--初始化消息列表。下拉加载消息列表-->
<script>

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }
    var html_name =  '与游客'+ getUrlParam('uid')+'的对话';
    $('#html_name').text(html_name);

    $(function () {
        $.ajax({
            url: '/app/websocket/test/getMessageListByUid.html',
            data: {
                'type':'s',
                'uid': getUrlParam('uid'),
                page: 1
            },
            type: "POST",
            dataType: "json",
            success: function (res) {
                var curPageData = res.data.data; // 接口返回的当前页数据列表
                //设置列表数据
                for (var i = 0; i < curPageData.length; i++) {
                    var newObj = curPageData[i];

                    if (newObj.from_client_id !== getUrlParam('uid')) {
                        //显示我发的
                        var html = '<li class="y-chat-mine">'
                            + ' <div class="y-chat-user"><img src="__PUBLIC__/static/img/tx.png"></div>'
                            + ' <div class="y-chat-text user-text"><cite class="my-time-tips r-time" style="">'+newObj.create_time+'</cite>' + newObj.message + '</div>'
                            + '</li>';
                    } else {
                        //显示用户发来的消息
                        var html = '<li class="customer-service-li">'
                            + ' <div class="y-chat-user"><img src="__PUBLIC__/static/img/tx2.png"></div>'
                            + ' <div class="y-chat-text user-text"><cite class="my-time-tips" style="">'+newObj.create_time+'</cite>' + newObj.message + '</div>'
                            + '</li>';
                    }

                    $('#msg-ul').append(html);

                }

                $('#mescroll').animate({scrollTop: $("#mescroll")[0].scrollHeight}, 100);

                $("#msg-ul").emojiParse({
                    icons: [
                        {
                            path: "dist/img/tieba/",
                            file: ".jpg",
                            placeholder: "#bd_{alias}#",
                        },
                        {
                            path: "dist/img/qq/",
                            file: ".gif",
                            placeholder: "#qq_{alias}#"
                        },
                        {
                            path: "dist/img/xl/",
                            file: ".png",
                            placeholder: "#xl_{alias}#"
                        }
                    ]
                });
            },
            error: function (e) {
                //联网失败的回调,隐藏下拉刷新和上拉加载的状态
            }
        });

    })
</script>
<!--END-->

<!--socket触发相关-->
<script language="javascript" type="text/javascript">
    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }

            } catch(e) {
                // console.log('error：'+str+'!!!'+e);
                return false;
            }
        }
        console.log('It is not a string!')
    }
    var sUid = 9527;//客服uid
    var ws_address = 'ws://my.sokect.com:7700';
    //【连接websocket--开始
    var websocket;
    startWebSocket(ws_address);
    function startWebSocket(ws) {
        websocket = new WebSocket(ws);
        websocket.onopen = function (evt) {
            onOpen(evt)
        };
        websocket.onclose = function (evt) {
            onClose(evt)
        };
        websocket.onmessage = function (evt) {
            onMessage(evt)
        };
        websocket.onerror = function (evt) {
            onError(evt)
        };
    }
    function onOpen(evt) {
    }
    //断开连接
    function onClose(evt) {
        websocket.close();
        console.log(evt);
    }
    //查看服务端响应消息
    function onMessage(evt) {
        if (!isJSON(evt.data)) {
            /**
             * bug记录： 用户连接后，服务端偶尔会触发，推送以下登录信息，导致json字符串格式错误
             * Hello 7f0000010b59000000a4
             * 7f0000010b59000000a4 login
             *
             * 理论上不应该这样。以下是服务端连接时，返回的信息
             $data = [
             'type' => 'onConnectSuccess',
             'client_id' => $client_id,
             'time' => time()
             ];
             Gateway::sendToCurrentClient(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
             */

            //解决方案一 重新加载
            // window.location.reload();

            //方案二 截取其中一段信息的client_id，直接绑定即可
            var arr = evt.data.split("Hello ");
            if (arr[1] !== undefined) {
                var cid = arr[1].replace(/ /g, '');
                console.log(cid);
                $.ajax({
                    type: "POST",
                    data: {
                        'uid': sUid,
                        'client_id': cid
                    },
                    url: "/app/websocket/test/bindClientId.html",
                    dataType: "json",
                    success: function (res) {
                        if (res.code) {
                            $.cookie('client_id', res.data.client_id);
                        }
                        console.log(res);
                    },
                    error: function (res) {
                        console.log(res);
                    }
                });
            }
            // console.log(evt.data);
            return false;
        }

        var dataObject = JSON.parse(evt.data);//JSON字符串转换成对象

        switch (dataObject.type) {
            case 'onConnectSuccess':
                //绑定用户id
                $.ajax({
                    type: "POST",
                    data: {
                        'uid': sUid,
                        'client_id': dataObject.client_id
                    },
                    url: "/app/websocket/test/bindClientId.html",
                    dataType: "json",
                    success: function (res) {
                        console.log(res);
                    },
                    error: function (res) {
                        console.log(res);
                    }
                });
                break;
            case 'ping':
                console.log('ping');
                break;
            default :
                //展示客户消息到对话列表
                if (dataObject.uid === getUrlParam('uid') ){
                    showMessageFromCustomerService(replace_em(dataObject.message));
                    console.log(dataObject);
                }

                break;
        }
    }
    //错误响应
    function onError(evt) {
        console.log(evt);
    }
    //连接websocket--结束】
    //指定年月日时分秒
    function getCurrentDate(date){
        var y = date.getFullYear();
        var m = date.getMonth()+1;
        var d = date.getDate();
        var h = date.getHours();
        var min = date.getMinutes();
        var s = date.getSeconds();
        var str=y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d)+' '+(h<10?('0'+h):h)+':'+(min<10?('0'+min):min)+':'+(s<10?('0'+s):s);
        return str;
    }
    //显示用户发来的消息
    function showMessageFromCustomerService(message) {
        var div = '<li class="customer-service-li">'
            +' <div class="y-chat-user"><img src="__PUBLIC__/static/img/tx2.png"></div>'
            +' <div class="y-chat-text user-text"><cite class="my-time-tips" style="">'+getCurrentDate(new Date())+'</cite>'+message+'</div>'
            +'</li>';
        var d = $("#msg-ul");
        var d=d[0];
        var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
        $("#msg-ul").append(div);
        if (doScroll) {
            d.scrollTop = d.scrollHeight - d.clientHeight;
        }
    }
    //追加显示我发送的消息
    function showSendMessage(message) {

        var div = '<li class="y-chat-mine">'
                +' <div class="y-chat-user"><img src="__PUBLIC__/static/img/tx.png"></div>'
                +' <div class="y-chat-text user-text"><cite class="my-time-tips r-time" style="">'+getCurrentDate(new Date())+'</cite>'+message+'</div>'
                +'</li>';
        var d = $("#msg-ul");
        var d=d[0];
        var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
        $("#msg-ul").append(div);
        if (doScroll) {
            d.scrollTop = d.scrollHeight - d.clientHeight;
        }
    }
</script>
<!--END-->

</body>
</html>
